package com.yiqi.zhiyuan.feature.home.view.adapter;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviType;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.utils.DateUtil;
import com.suozhang.framework.utils.DensityUtil;
import com.suozhang.framework.utils.LocationUtils;
import com.suozhang.framework.utils.RxClipboardTool;
import com.suozhang.framework.utils.T;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.common.map.AMapUtil;
import com.yiqi.zhiyuan.common.utils.AppUtil;
import com.yiqi.zhiyuan.entity.vo.OrderVO;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 立即前往弹框
 *
 * @author LIJUWEN
 * @email yiyayiyayaoljw@gmail.com
 * @date 2017/4/25 15:22
 */
public class GrabOrderDialog extends Dialog implements RouteSearch.OnRouteSearchListener {


    @BindView(R.id.titleTextView)
    TextView mTitleTextView;
    @BindView(R.id.contentTextView)
    TextView mContentTextView;
    @BindView(R.id.tv_card_order_time)
    TextView mTvCardOrderTime;
    @BindView(R.id.tv_card_order_distance)
    TextView mTvCardOrderDistance;
    @BindView(R.id.iv_start_pos)
    ImageView mIvStartPos;
    @BindView(R.id.iv_end_pos)
    ImageView mIvEndPos;
    @BindView(R.id.tv_card_order_departure)
    TextView mTvCardOrderDeparture;
    @BindView(R.id.tv_card_order_waypoint1)
    TextView mTvCardOrderWaypoint1;
    @BindView(R.id.tv_card_order_waypoint2)
    TextView mTvCardOrderWaypoint2;
    @BindView(R.id.tv_card_order_destination)
    TextView mTvCardOrderDestination;
    @BindView(R.id.btn_card_order_map)
    TextView mBtnCardOrderMap;
    @BindView(R.id.tv_order_remark)
    TextView mTvOrderRemark;
    @BindView(R.id.btn_order_look_up)
    ImageView mBtnOrderLookUp;
    @BindView(R.id.tv_order_count_down)
    TextView mTvOrderCountDown;
    @BindView(R.id.btn_card_order_grab)
    LinearLayout mBtnCardOrderGrab;
    @BindView(R.id.tv_card_order_dis)
    TextView mTvCardOrderDis;
    @BindView(R.id.btn_immediately_exit)
    ImageView mBtnImmediatelyExit;

    @BindView(R.id.tv_card_order_flightno)
    TextView mTvImmediatelyFlightNo;
    private Context context;


    private MyClickListenerInterface listenerInterface;
    private LayoutInflater layoutInflater;
    OrderVO orderVO;
    private RouteSearch routeSearch;
    private RouteSearch.FromAndTo fromAndTo;
    private AMapLocation amapLocation;

    public GrabOrderDialog(Context context, OrderVO orderVO, AMapLocation amapLocation) {
        super(context, R.style.ActionImmediatelyDialogStyle);
        this.context = context;
        this.orderVO = orderVO;
        this.amapLocation = amapLocation;
        layoutInflater = LayoutInflater.from(context);
        routeSearch = new RouteSearch(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        if (amapLocation != null) {
            LatLonPoint mStartPoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());
            LatLonPoint mEndPoint = new LatLonPoint(orderVO.getDepLatitude(), orderVO.getDepLongitude());
            fromAndTo = new RouteSearch.FromAndTo(
                    mStartPoint, mEndPoint);
            routeSearch.setRouteSearchListener(this);
            // fromAndTo包含路径规划的起点和终点，drivingMode表示驾车模式
            // 第三个参数表示途经点（最多支持16个），第四个参数表示避让区域（最多支持32个），第五个参数表示避让道路
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "");
            routeSearch.calculateDriveRouteAsyn(query);
        }

    }

    private void init() {
        View view = layoutInflater.inflate(R.layout.dialog_order_grab, null);
        ButterKnife.bind(this, view);
        setContentView(view);
        onGetCode();

        mTvCardOrderDeparture.setText(orderVO.getDeparture());
        mTvCardOrderDestination.setText(orderVO.getDestination());

        if (orderVO.getUseCarType() == 1) {//接机单
            mTvImmediatelyFlightNo.setVisibility(View.VISIBLE);
            mTvImmediatelyFlightNo.setText("航班号:" + orderVO.getFlightNo());
            mTvCardOrderTime.setText(DateUtil.stampToDate2(Long.parseLong(orderVO.getFlightTime())));
        } else if (orderVO.getUseCarType() == 0) {//用车
            mTvImmediatelyFlightNo.setVisibility(View.GONE);
            if (orderVO.getOrderType() == 0) {//现在
                mTvCardOrderTime.setText("马上用车");
            } else if (orderVO.getOrderType() == 1) {//预约
                mTvCardOrderTime.setText(TextUtils.isEmpty(orderVO.getReserveTime()) ? "" : DateUtil.getDayString(Long.parseLong(orderVO.getReserveTime())));
            } else if (orderVO.getOrderType() == 2) {//代叫
                if (orderVO.getOrderFlag() == 0) {//现在出发
                    mTvCardOrderTime.setText("马上用车");
                } else if (orderVO.getOrderFlag() == 1) {//预约时间
                    mTvCardOrderTime.setText(TextUtils.isEmpty(orderVO.getReserveTime()) ? "" : DateUtil.getDayString(Long.parseLong(orderVO.getReserveTime())));
                }
            }
        } else if (orderVO.getUseCarType() == 2) {
            mTvImmediatelyFlightNo.setVisibility(View.GONE);
            if (orderVO.getOrderType() == 0) {//现在出发
                mTvCardOrderTime.setText("马上用车");
            } else if (orderVO.getOrderType() == 1) {//预约时间
                mTvCardOrderTime.setText(TextUtils.isEmpty(orderVO.getReserveTime()) ? "" : DateUtil.getDayString(Long.parseLong(orderVO.getReserveTime())));
            } else if (orderVO.getOrderType() == 2) {
                if (orderVO.getOrderFlag() == 0) {//现在出发
                    mTvCardOrderTime.setText("马上用车");
                } else if (orderVO.getOrderFlag() == 1) {//预约时间
                    mTvCardOrderTime.setText(TextUtils.isEmpty(orderVO.getReserveTime()) ? "" : DateUtil.getDayString(Long.parseLong(orderVO.getReserveTime())));
                }
            }
        }


        mTvOrderRemark.setText(TextUtils.isEmpty(orderVO.getMessages()) ? "暂无备注" : orderVO.getMessages());
        mTvCardOrderWaypoint1.setVisibility(TextUtils.isEmpty(orderVO.getWaypoint1()) ? View.GONE : View.VISIBLE);
        mTvCardOrderWaypoint2.setVisibility(TextUtils.isEmpty(orderVO.getWaypoint2()) ? View.GONE : View.VISIBLE);
        mTvCardOrderWaypoint1.setText(TextUtils.isEmpty(orderVO.getWaypoint1()) ? "" : "途径点：" + orderVO.getWaypoint1());
        mTvCardOrderWaypoint2.setText(TextUtils.isEmpty(orderVO.getWaypoint2()) ? "" : "途径点：" + orderVO.getWaypoint2());
        mTvCardOrderDistance.setText("全程预计" + orderVO.getDistance() + "公里");
        mTvImmediatelyFlightNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxClipboardTool.copyText(AM.app(), orderVO.getFlightNo());
                T.showShort("航班号已复制");
            }
        });

        //获取当前Activity所在的窗体
        Window dialogWindow = getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
    }

    @Override
    public void show() {
        super.show();

        try {
            /**
             * 设置宽度全屏，要设置在show的后面
             */
            WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
            layoutParams.gravity = Gravity.CENTER;
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

            getWindow().getDecorView().setPadding(DensityUtil.dp2px(43), 0, DensityUtil.dp2px(43), 0);
            getWindow().setAttributes(layoutParams);
        } catch (Exception e) {
            T.showShort(e.getMessage());
        }


    }

    public void setListener(MyClickListenerInterface listener) {
        this.listenerInterface = listener;
    }

    @OnClick({R.id.btn_card_order_map, R.id.btn_card_order_grab, R.id.btn_immediately_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_card_order_map:
                if (orderVO == null) return;
                if (LocationUtils.isGpsEnabled()) {
                    List<Poi> wayList = AMapUtil.convertPoiList2(orderVO);//途径点目前最多支持3个。
                    Poi start = new Poi(orderVO.getDeparture(), new LatLng(orderVO.getDepLatitude(), orderVO.getDepLongitude()), "");
                    Poi end = new Poi(orderVO.getDestination(), new LatLng(orderVO.getDesLatitude(), orderVO.getDesLongitude()), "");
                    AmapNaviPage.getInstance().showRouteActivity(context, new AmapNaviParams(start, wayList, end, AmapNaviType.DRIVER), null);
                } else {
                    T.showShort("请先打开gps");
                }
                break;
            case R.id.btn_card_order_grab:
                if (listenerInterface != null) {
                    dismiss();
                    listenerInterface.doConfirm(orderVO);
                } else {
                    dismiss();
                }
                break;
            case R.id.btn_immediately_exit:
                dismiss();
                break;
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                DrivePath walkPath = result.getPaths().get(0);
                mTvCardOrderDis.setText(AppUtil.formatFloat(walkPath.getDistance() / 1000));
            } else {
//                T.showShort(R.string.toast_no_result);
            }
        } else {

        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    public interface MyClickListenerInterface {
        void doConfirm(OrderVO orderVO);
    }


    public void onGetCode() {
        final int count = 60;//倒计时60秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {
                mTvOrderCountDown.setText(String.format("00′%s″", num));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                dismiss();
            }
        });

    }
}
